<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------
// | Author: JiYun Date:2019-05-08 Time:18:12
// +----------------------------------------------------------------------

namespace app\common\service\system;

use app\common\service\BaseService;
use app\common\model\system\SystemUser as SystemUserModel;

/**
 * Class SystemUser
 * @author JiYun On 2019/05/09
 * @package app\common\service\system
 */
final class SystemUser extends BaseService
{
    public function __construct()
    {
        parent::__construct();
    }
    
    /**
     * 登录验证
     * @author JiYun On 2019/05/09
     * @param $username
     * @param $password
     * @param $ip
     * @return mixed|null
     */
    public function login($username, $password, $ip)
    {
        if (empty($username) || empty($password)) {
            return null;
        }
        
        // 用户名和密码验证
        $user   = new SystemUserModel();
        $result = $user->checkUser($username, $password);
        
        if ($result === null) {
            return null;
        }
        
        // 生成 token
        $userToken = new SystemUserToken();
        $token     = $userToken->getToken($result['id']);
        
        $result['token'] = $token;
        
        // 更新最后登录时间和IP地址
        $this->updateLogin($result['id'], $ip);
        
        // 写入登录日志
        $loginLog = new SystemUserLoginLog();
        $loginLog->saveLog($result['id'], $result['username'], $ip);
        
        return $result;
    }
    
    /**
     * 更新最后登录时间和IP地址
     * @author JiYun On 2019/05/09
     * @param string $id
     * @param string $ip
     */
    public function updateLogin($id = '', $ip = '')
    {
        $data = [
            'last_login_time' => date('Y/m/d H:i:s', time()),
            'last_login_ip'   => $ip
        ];
        
        $where = [
            'id' => $id
        ];
        
        $user = new SystemUserModel();
        $user->updateLogin($where, $data);
    }
    
    /**
     * 退出系统
     * @author JiYun On 2019/05/09
     * @param string $token
     * @return bool
     */
    public function logout($token = '')
    {
        if (empty($token)) {
            return false;
        }
        
        $userToken = new SystemUserToken();
        $result    = $userToken->expireToken($token);
        
        return $result;
    }
}
